package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.StringUtils;
import com.jsoniter.JsonIterator;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.bo.common.conf.util.HttpUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.net.ssl.HostnameVerifier;
import java.io.*;
import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class InfinityCashService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(InfinityCashService.class);

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private InfinityCashS1Service infinityCashS1Service;
    @Autowired
    private InfinityCashD0Service infinityCashD0Service;

    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("infinitycash", this);
        BaseJobHandler.merchantAndServiceMap.put("raisecash", this);
        BaseJobHandler.merchantAndServiceMap.put("papamoney", this);
        BaseJobHandler.merchantAndServiceMap.put("papamoney2", this);
        BaseJobHandler.merchantAndServiceMap.put("papamoney3", this);
        BaseJobHandler.merchantAndServiceMap.put("papamoney4", this);
    }

    public String getCode(CeAgentAccountEntity agentAccount) {
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
            long key = Math.round((Math.random() + 1) * 10000000000000000L);

            String url = merchant.getApiDomain() + "/api/manage/auth/captcha?key=0."+key;
            LOGGER.info("== 开始请求登录接口 ==,url:{}", url);
            Map<String, String> headers = getHeaders(agentAccount);
            JSONObject params = new JSONObject();
            String result = HttpUtil.postPageSsLV(url, headers, params.toString());
            LOGGER.info("== 开始请求登录接口 ==,result:{}", result);
            if (StringUtils.isNotEmpty(JsonIterator.deserialize(result).get("data").toString())) {
                LOGGER.error("== 开始请求登录接口 成功==，data:{}", JsonIterator.deserialize(result).get("data").toString());
                JSONObject requestHeader = new JSONObject();
                requestHeader.put("refreshToken", JsonIterator.deserialize(result).get("data").get("refreshToken").toString());
                requestHeader.put("Authorization", JsonIterator.deserialize(result).get("data").get("accessToken").toString());
                requestHeader.put("Content-Type", "application/json");
                agentAccount.setRequestHeader(requestHeader.toString());
                agentAccount.setLoginDt(new Date());
                agentAccount.setLoginStatus(1);
                agentAccountDao.updateByPrimaryKey(agentAccount);
            }
            return result;
    }
    public String login(CeAgentAccountEntity agentAccount,String code,String key) {
        if (agentAccount.getMerchantCode().contains("papamoney")) {
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
            String url = merchant.getApiDomain() + "/api/manage/auth/login";
            LOGGER.info("== 开始请求登录接口 ==,url:{}", url);
            Map<String, String> headers = getHeaders(agentAccount);
            String copyKey = "0." + key;
            double v = Double.parseDouble(copyKey);
            JSONObject params = new JSONObject();
            params.put("username", agentAccount.getAccount());
            params.put("password", agentAccount.getExtraInfo());
            params.put("code", code);
            params.put("key", v);
            String result = HttpUtil.postPageSsLV(url, headers, params.toString());
            LOGGER.info("== 开始请求登录接口 ==,result:{}", result);
            if (StringUtils.isNotEmpty(JsonIterator.deserialize(result).get("data").toString())) {
                LOGGER.error("== 开始请求登录接口 成功==，data:{}", JsonIterator.deserialize(result).get("data").toString());
                JSONObject requestHeader = new JSONObject();
                requestHeader.put("refreshToken", JsonIterator.deserialize(result).get("data").get("refreshToken").toString());
                requestHeader.put("Authorization", JsonIterator.deserialize(result).get("data").get("accessToken").toString());
                requestHeader.put("Content-Type", "application/json");
                agentAccount.setRequestHeader(requestHeader.toString());
                agentAccount.setLoginDt(new Date());
                agentAccount.setLoginStatus(1);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return "登陆成功";
            }
            return "登陆失败";
        }
        return "只接受PapaMoney";
    }


    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (agentAccount.getStage().contains("d")) {
            return infinityCashD0Service.hasLogin(agentAccount);
        } else {
            return infinityCashS1Service.hasLogin(agentAccount);
        }
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        if (agentAccount.getStage().contains("d")) {
            infinityCashD0Service.refresh(agentAccount);
        } else {
            infinityCashS1Service.refresh(agentAccount);
        }
    }


    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        if (agentAccount.getStage().contains("d")) {
            LOGGER.info("== 拉取D阶段数据 ==");
            infinityCashD0Service.updateOrderList(agentAccount);
        } else {
            LOGGER.info("== 拉取S阶段数据 ==");
            infinityCashS1Service.updateOrderList(agentAccount);
        }
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {
        if (agentAccount.getStage().contains("d")) {
            infinityCashD0Service.updateOrderDetailInfo(agentAccount);
        } else {
            infinityCashS1Service.updateOrderDetailInfo(agentAccount);
        }
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        if (agentAccount.getStage().contains("d")) {
            infinityCashD0Service.compostCollectionData(agentAccount);
        } else {
            infinityCashS1Service.compostCollectionData(agentAccount);
        }

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        if (agentAccount.getStage().contains("d")) {
            infinityCashD0Service.checkOrdersPaidStatus(agentAccount);
        } else {
            infinityCashS1Service.checkOrdersPaidStatus(agentAccount);
        }

    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        if (agentAccount.getStage().contains("d")) {
            infinityCashD0Service.updatePaidOrderToCollection(agentAccount);
        } else {
            infinityCashS1Service.updatePaidOrderToCollection(agentAccount);
        }
    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        if (agentAccount.getStage().contains("d")) {
            infinityCashD0Service.updateRemovedOrderToCollection(agentAccount);
        } else {
            infinityCashS1Service.updateRemovedOrderToCollection(agentAccount);
        }

    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        if (account.getStage().contains("d")) {
            return infinityCashD0Service.sendNote(ceCommentPushLogEntity);
        } else {
            return infinityCashS1Service.sendNote(ceCommentPushLogEntity);
        }
    }

    @Override
    public String updateRepaymentLink(String collectionNo,boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        if (accountEntity.getStage().contains("d")) {
            return infinityCashD0Service.updateRepaymentLink(collectionNo,isReduce);
        } else {
            return infinityCashS1Service.updateRepaymentLink(collectionNo,isReduce);
        }
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());


        String renewLink = "No Link";
        return renewLink;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        return "";
    }

    @Override
    public String queryPaymentOrderResult(String orderNo,String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        return null;
    }

    public static void main(String[] args) {
       double a = 10034798643912D;
       double b = 10 * String.valueOf(a).length()/a;
       String c = String.valueOf(b);
       LOGGER.info("=== B ===,b:{}",c);
    }
}
